<template>
  <div class="home-container layout-pd">

    <el-card shadow="hover" :body-style="{ paddingBottom: 0 }">
      <el-form :model="state.sensor.formParam" label-position="top" ref="queryFormRef" :inline="true"
               label-width="100px">
        <el-row :gutter="20">
            <el-form-item label="工作地点" prop="workPlace">
              <el-select
                  v-model="state.sensor.formParam.workPlace"
                  filterable
                  placeholder="请选择一个工作地点"
                  style="width: 240px"
              >
                <el-option
                    v-for="item in state.sensor.options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>

            </el-form-item>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-row :gutter="15" class="home-card-three">
        <el-col>
          <div class="home-card-item">
            <div style="height: 100%" ref="homeBarRef"></div>
          </div>
        </el-col>
        <!--			</el-col>-->
      </el-row>
    </el-card>

  </div>
</template>

<script setup lang="ts" name="home">
import {markRaw, nextTick, onActivated, onDeactivated, onMounted, reactive, ref, watch} from 'vue';
import * as echarts from 'echarts';
import {storeToRefs} from 'pinia';
import {useThemeConfig} from '/@/stores/themeConfig';
import {useTagsViewRoutes} from '/@/stores/tagsViewRoutes';
import sensorApi from '/@/api/manager/sensor';
import workerApi from '/@/api/manager/worker';
import {getTodayZeroTimestamp} from '/@/utils/formatTime';
import {onUnmounted} from "@vue/runtime-core";

// 定义变量内容
const homeBarRef = ref();
const storesTagsViewRoutes = useTagsViewRoutes();
const storesThemeConfig = useThemeConfig();
const {themeConfig} = storeToRefs(storesThemeConfig);
const {isTagsViewCurrenFull} = storeToRefs(storesTagsViewRoutes);
const state = reactive({
  global: {
    sensorDashboard: null,
    dispose: [null, '', undefined],
  } as any,

  myCharts: [] as EmptyArrayType,
  charts: {
    theme: '',
    bgColor: '',
    color: '#303133',
  },
  sensor: {
    timerId: 0 as number,
    formParam: {
      startTime: getTodayZeroTimestamp(),
      workPlace: '',
    },

    select: {
      loading: false
    },
    options: [] as EmptyArrayType,
    sensorDataList: [] as EmptyArrayType,
  },

});

state.sensor.sensorDataList = markRaw([])

const fetchOptions = () => {
  workerApi.workPlaceList().then(res => {
    var list = res.data.list
    if (list && list.length > 0) {
      state.sensor.options = list.map((item: any) => {
        return {value: `${item}`, label: `${item}`}
      })
      state.sensor.formParam.workPlace=state.sensor.options[0].value
    }
  })
}
// 初始化表格数据
const handleQuery = () => {
  state.sensor.formParam.startTime = getTodayZeroTimestamp();
  state
  return sensorApi.query(state.sensor.formParam).then((res) => {
    var sensorList = res.data.list;
    if (!sensorList || sensorList.length === 0) {
      return;
    }
    var echatList = sensorList.map((item: any) => {
      return [
        item.gmtCreate,
        item.pressure
      ]
    })
    state.sensor.sensorDataList = echatList
  });
};

// 柱状图
const initBarChart = () => {
  if (!state.global.dispose.some((b: any) => b === state.global.sensorDashboard)) state.global.sensorDashboard.dispose();
  state.global.sensorDashboard = markRaw(echarts.init(homeBarRef.value, state.charts.theme));
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        return params[0].value[1] + "测试疏忽<br/>是否";
      },
      axisPointer: {
        animation: false
      }
    },
    grid: {
      x: 35,
      y: 35,
      x2: 35,
      y2: 35
    },
    xAxis: {
      type: 'time',
      splitLine: {
        show: false
      },
      triggerEvent: true
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: false
      }
    },
    series: [{
      name: '模拟数据1',
      type: 'line',
      smooth: true,
      showSymbol: false,
      hoverAnimation: false,
      data: state.sensor.sensorDataList
    }
    ],
  }
  state.global.sensorDashboard.setOption(option);
  state.myCharts.push(state.global.sensorDashboard);
};
// 批量设置 echarts resize
const initEchartsResizeFun = () => {
  nextTick(() => {
    for (let i = 0; i < state.myCharts.length; i++) {
      setTimeout(() => {
        state.myCharts[i].resize();
      }, i * 1000);
    }
  });
};
// 批量设置 echarts resize
const initEchartsResize = () => {
  window.addEventListener('resize', initEchartsResizeFun);
};


const initEcharts = (startTime: number) => {
  sensorApi.query({
    workPlace: state.sensor.formParam.workPlace,
    startTime: startTime
  }).then((res) => {
    var sensorList = res.data.list;
    if (!sensorList || sensorList.length === 0) {
      return;
    }
    var echatList = sensorList.map((item: any) => {
      return {
        name: item.workPlace,
        value: [
          item.gmtCreate,
          item.pressure
        ]
      };
    })
    state.sensor.sensorDataList.push(...echatList)
  })
}

// 页面加载时
onMounted(() => {
  initEchartsResize();
  fetchOptions();
});

onUnmounted(() => {
  clearInterval(state.sensor.timerId);
})

onDeactivated(() => {
  clearInterval(state.sensor.timerId)
})

// 由于页面缓存原因，keep-alive
onActivated(() => {
  initEchartsResizeFun();
});
// 监听 pinia 中的 tagsview 开启全屏变化，重新 resize 图表，防止不出现/大小不变等
watch(
    () => isTagsViewCurrenFull.value,
    () => {
      initEchartsResizeFun();
    }
);
// 监听 pinia 中是否开启深色主题
watch(
    () => themeConfig.value,
    (isIsDark) => {
      nextTick(() => {
        state.charts.theme = isIsDark ? 'dark' : '';
        state.charts.bgColor = isIsDark ? 'transparent' : '';
        state.charts.color = isIsDark ? '#dadada' : '#303133';
        handleQuery().then(() => {
          initBarChart();
        });
        var startTime = new Date().getTime()
        state.sensor.timerId =
            setInterval(() => {
              initEcharts(startTime)
              state.global.sensorDashboard.setOption({
                series: [
                  {
                    data: state.sensor.sensorDataList
                  }
                ]
              });
              startTime = new Date().getTime()
            }, 5000)
      });
    },
    {
      deep: true,
      immediate: true,
    }
);
</script>

<style scoped lang="scss">
$homeNavLengh: 8;

.home-container {
  overflow: hidden;

  .home-card-one,
  .home-card-two,
  .home-card-three {
    .home-card-item {
      width: 100%;
      height: 130px;
      border-radius: 4px;
      transition: all ease 0.3s;
      overflow: hidden;
      background: var(--el-color-white);
      color: var(--el-text-color-primary);
      border: 1px solid var(--next-border-color-light);

      &:hover {
        box-shadow: 0 2px 12px var(--next-color-dark-hover);
        transition: all ease 0.3s;
      }

      &-icon {
        width: 70px;
        height: 70px;
        border-radius: 100%;
        flex-shrink: 1;

        i {
          color: var(--el-text-color-placeholder);
        }
      }

      &-title {
        font-size: 15px;
        font-weight: bold;
        height: 30px;
      }
    }
  }

  .home-card-one {
    @for $i from 0 through 3 {
      .home-one-animation#{$i} {
        opacity: 0;
        animation-name: error-num;
        animation-duration: 0.5s;
        animation-fill-mode: forwards;
        animation-delay: calc($i / 4) s;
      }
    }
  }

  .home-card-two,
  .home-card-three {
    .home-card-item {
      height: 400px;
      width: 100%;
      overflow: hidden;

      .home-monitor {
        height: 100%;

        .flex-warp-item {
          width: 25%;
          height: 111px;
          display: flex;

          .flex-warp-item-box {
            margin: auto;
            text-align: center;
            color: var(--el-text-color-primary);
            display: flex;
            border-radius: 5px;
            background: var(--next-bg-color);
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
              background: var(--el-color-primary-light-9);
              transition: all 0.3s ease;
            }
          }

          @for $i from 0 through $homeNavLengh {
            .home-animation#{$i} {
              opacity: 0;
              animation-name: error-num;
              animation-duration: 0.5s;
              animation-fill-mode: forwards;
              animation-delay: calc($i / 10) s;
            }
          }
        }
      }
    }
  }
}
</style>
